import axios from '@/utils/request'

export default {
  Album: {
    list: {
      list_display: [
        'id',
        'title',
        'type',
        'comment'
      ]
    },
    form: {
      fields: [
        'title',
        'type',
        { property: 'pictures', type: 'images' },
        'comment'
      ]
    }
  },

  Picture: {
    list: {
      list_display: [
        'id',
        { property: 'image', type: 'image' },
        {
          property: 'album',
          component: {
            props: ['data'],
            render(h) {
              return <p> {
                this.data.map(item => {
                  return <el-tag>{item.__toString}</el-tag>
                })
              } </p>
            }
          }
        },
        'title',
        'type'
      ]
    },
    form: {
      fields: [
        'album',
        'title',
        'type',
        { property: 'image', type: 'image' },
        'comment'
      ]
    }
  },

  Balance: {
    form: {
      fields: [
        'user',
        {
          property: 'frozen',
          field_options: {
            label: '禁止提现额度'
          },
          help: '用户可提现金额为当前余额-禁止提现额度，禁止提现额度会根据余额支付同步扣减'
        }
      ]
    },
    list: {
      query: {
        '@order': 'entity.id|DESC'
      },
      disabled_actions: ['new', 'delete'],
      list_filter: {
        usernameOrNickname: {
          expression: 'entity.getUser().__toString() matches "/:value/"',
          label: '用户名 / 电话',
          type: 'input'
        }
      },
      list_display: [
        'id',
        'user',
        'amount',
        {
          property: 'frozen',
          label: '禁止提现额度'
        },
        {
          property: 'user',
          label: '总收入|总支出|理论余额',
          component: {
            props: ['data', 'record'],
            data() {
              return {
                income: '计算中...',
                expenditure: '计算中...',
                amount: '点击计算'
              }
            },
            created() {
            },
            render(h) {
              return <div onClick={() => {
                this.axios.get(`/manage/transactions`, {
                  params: {
                    '@filter': `entity.getTo().getId() == ${this.data.id}`,
                    '@select': `SUM(entity.amount) as amount`
                  }
                }).then((res) => {
                  console.log('收入', res.data)
                  this.income = res.data[0].amount
                  this.axios.get(`/manage/transactions`, {
                    params: {
                      '@filter': `entity.getFrom().getId() == ${this.data.id}`,
                      '@select': `SUM(entity.amount) as amount`
                    }
                  }).then((res) => {
                    console.log('支出', res.data)
                    this.expenditure = res.data[0].amount
                    this.amount = (this.income - this.expenditure).toFixed(2)
                  })
                })
              }}>{this.amount}</div>
            }
          }
        },
        // {
        //   property: 'user',
        //   label: '富友姓名',
        //   component: {
        //     props: ['data'],
        //     data() {
        //       return {
        //         name: ''
        //       }
        //     },
        //     created() {
        //       this.axios.get(`/manage/fuiou-accounts`, {
        //         params: { '@filter': `entity.getUser().getId() == ${this.data.id}` }
        //       }).then((res) => {
        //         console.log(res.data)
        //         if (res.data.length > 0) {
        //           this.name = res.data[0].outAcntNm
        //         }
        //       })
        //     },
        //     render(h) {
        //       return <span>{this.name}</span>
        //     }
        //   }
        // },
        // {
        //   property: 'user',
        //   label: '汇付姓名',
        //   component: {
        //     props: ['data'],
        //     data() {
        //       return {
        //         name: ''
        //       }
        //     },
        //     created() {
        //       this.axios.get(`/manage/huifu-accounts`, {
        //         params: { '@filter': `entity.getUser().getId() == ${this.data.id}` }
        //       }).then((res) => {
        //         console.log(res.data)
        //         if (res.data.length > 0) {
        //           this.name = res.data[0].cardInfo.card_name
        //         }
        //       })
        //     },
        //     render(h) {
        //       return <span>{this.name}</span>
        //     }
        //   }
        // },
        'lastModifiedTime'
      ]
    }
  },

  BalanceLog: {
    form: {
      fields: '__all__'
    },
    list: {
      export: {
        query: {
          '@display': `{
            'id' : 'entity.getId()',
            'source' : 'entity.getSource()',
            'user' : 'entity.getUser().getUsername()',
            'before' : 'entity.getBefore()',
            'amount' : 'entity.getAmount()',
            'after' : 'entity.getAfter()',
            'comment' : 'entity.getComment()',
            'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")'
          }`,
          limit: 10000000
        },
        label: {
          'id': 'id',
          'source': '来源',
          'user': '收款人',
          'before': '前',
          'amount': '金额',
          'after': '后',
          'comment': '备注',
          'createdTime': '创建时间'
        }
      },
      query: {
        '@order': 'entity.id|DESC'
      },
      disabled_actions: ['new', 'edit', 'delete', 'lines'],
      list_filter: {
        usernameOrNickname: {
          expression: 'entity.getUser().getUsername() matches ":value"',
          label: '用户名 / 电话',
          type: 'input'
        },
        amount: {
          expression: 'entity.getAmount() :value 0',
          label: '类型',
          data: [
            { value: '>=', label: '收入' },
            { value: '<', label: '支出' }
          ]
        },
        beforeCreatedTime: {
          expression: 'entity.getCreatedTime() >= datetime.get(":value")',
          label: '创建开始时间',
          type: 'datetime'
        },
        afterCreatedTime: {
          expression: 'entity.getCreatedTime() < datetime.get(":value")',
          label: '创建结束时间',
          type: 'datetime'
        },
        comment: '备注'
      },
      list_display: [
        'id',
        'source',
        {
          property: 'user',
          label: '收款人'
        },
        // 'type',
        'before',
        {
          property: 'amount',
          component: {
            props: ['data'],
            render(h) {
              return (
                <span>{this.data >= 0 ? '+' : ''}{this.data}</span>
              )
            }
          }
        },
        'after',
        'comment',
        'createdTime'
      ]
    }
  },

  Content: {
    form: {
      fields: [
        'title',
        {
          property: 'category',
          relation_filter: {
            '@filter': 'entity.getType().getSlug() == "content"',
            '@order': 'entity.id|ASC'
          }
        },
        { property: 'cover', type: 'image' },
        {
          property: 'video',
          field_options: { label: '视频链接' },
          help: '请复制可以直接访问的视频链接'
        },
        {
          property: 'onlyStaffVisible',
          field_options: { label: '仅员工可看' },
          help: '设置了仅员工可见的，就不能分享'
        },
        {
          property: 'extraData',
          component: {
            props: ['form', 'property'],
            data() {
              return {
                item: {
                  visit_limit: 99999
                },
                label: {
                  visit_limit: '可查看次数'
                }
              }
            },
            methods: {
              // 获取数据有字段再初始化数据
              setConfig(value) {
                if (Object.keys(value).includes('extraData')) {
                  if (!value.extraData) {
                    return
                  }
                  if (value.extraData.visit_limit) {
                    console.log(value.extraData.visit_limit)
                    this.item.visit_limit = value.extraData.visit_limit
                  }
                }
              },
              updateProperty() {
                this.form[this.property] = this.item
              }
            },
            watch: {
              // immediate监听form
              'form': {
                handler(value, oldValue) {
                  this.setConfig(value)
                },
                immediate: true
              }
            },
            render(h) {
              return (
                <div>
                  {
                    Object.keys(this.item).map(v => {
                      // 特殊的，非勾选的设置项
                      const noDefaultConfig = ['visit_limit']
                      if (noDefaultConfig.indexOf(v) === -1) {
                        return <div><el-checkbox label={this.label[v]} v-model={this.item[v]} onChange={() => this.updateProperty()} /></div>
                      }
                    })
                  }
                  <div>
                    <span>{this.label['visit_limit']}</span>&nbsp;&nbsp;
                    <el-input-number v-model={this.item['visit_limit']} step={1} min={0} onChange={() => this.updateProperty()}></el-input-number>
                  </div>
                </div >
              )
            }
          }
        },
        {
          property: 'enabled',
          field_options: { label: '是否上架' },
          help: '上架才能查看'
        },
        'content'
      ]
    },
    list: {
      query: {
        '@order': 'entity.id|DESC'
      },
      list_filter: {
        'category.parent.id': () => {
          return axios
            .get(`/manage/categories`, { params: { '@filter': `!entity.getParent() && entity.getType().getSlug() == "content"` } })
            .then(res =>
              Object.assign(
                { __label: '一级分类' },
                ...res.data.map(v => {
                  return { [v.id]: `${v.name}` }
                })
              )
            )
        },
        'category.id': () => {
          return axios
            .get(`/manage/categories`, { params: { '@filter': `entity.getParent() && entity.getType().getSlug() == "content"`, '@expands': "['entity.parent']" } })
            .then(res =>
              Object.assign(
                { __label: '二级分类' },
                ...res.data.map(v => {
                  return { [v.id]: `${v.name}` }
                })
              )
            )
        },
        'name': '标题'
      },
      list_display: [
        'id',
        { property: 'cover', type: 'image' },
        'category',
        {
          property: 'enabled',
          label: '上架',
          editable: true
        },
        {
          property: 'onlyStaffVisible',
          label: '仅员工可见',
          editable: true
        },
        'title',
        'createdTime'
      ]
    }
  },

  Category: {
    form: {
      fields: [
        'name',
        'type',
        { property: 'parent', required: false },
        { property: 'enabled', required: false, default_value: true },
        { property: 'sequence', required: false, default_value: 0 },
        { property: 'icon', required: false, type: 'image' }
      ]
    },
    list: {
      list_display: ['id', 'type', 'name', 'parent', 'enabled', 'sequence'],
      list_filter: {
        'type.id': () => {
          return axios
            .get('/manage/types')
            .then(res =>
              Object.assign({ __label: '类型' },
                ...res.data.map(v => { return { [v.id]: v.name } })
              )
            )
        },
        'parent.id': () => {
          return axios
            .get('/manage/categories')
            .then(res =>
              Object.assign({ __label: '上级分类' },
                ...res.data.map(v => { return { [v.id]: v.name } })
              )
            )
        }
      }
    }
  },

  Option: {
    form: {
      fields: [
        { property: 'name', type_options: { disabled: true } },
        'value'
      ]
    },
    list: {
      disabled_actions: ['new', 'delete'],
      list_display: ['id', 'name', 'value', 'readable']
    }
  },

  Type: {
    form: {
      fields: '__all__'
    },
    list: {
      list_display: ['id', 'name', 'slug']
    }
  },

  User: {
    form: {
      fields: [
        { property: 'username', field_options: { label: '用户名' } },
        'phone',
        { property: 'email', field_options: { label: 'Email' } },
        { property: 'enabled', type: 'boolean', default_value: true, field_options: { label: '是否启用？' } },
        { property: 'plainPassword', field_options: { label: '密码' } }
      ]
    },
    list: {
      list_filter: {
        username: {
          expression: 'entity.getUsername() matches ":value"',
          label: '用户名',
          type: 'input'
        }
      },
      list_display: [
        'id',
        { property: 'username', label: '用户名' },
        { property: 'enabled', type: 'boolean', label: '是否启用' },
        'createdTime'
      ]
    }
  },

  UserProfile: {
    form: {
      fields: '__all__'
    },
    list: {
      disabled_actions: ['new', 'delete', 'edit', 'lines'],
      list_display: [
        'id',
        { property: 'avatarUrl', type: 'image' },
        'nickname',
        'user',
        {
          property: 'amount',
          label: '余额',
          component: {
            props: ['scope'],
            data() {
              return { amount: 0 }
            },
            created() {
              axios.get(
                `/manage/users/${this.scope.row.user.id}`,
                { params: { '@expands': "['entity.balance']" } }
              ).then((res) => {
                console.log(res)
                if (res.data.balance != null) {
                  this.amount = res.data.balance.__metadata.amount
                }
              })
            },
            render(h) {
              return (
                <el-tag>{this.amount}</el-tag>
              )
            }
          }
        }
      ]
    }
  }
}
